<template>
  <div>
    <el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" />
      </el-form-item>
      <el-form-item label="入职时间" prop="timeOfEntry">
        <el-date-picker v-model="form.timeOfEntry" format="yyyy年MM月dd日" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <el-select v-model="form.formOfEmployment" placeholder="请选择活动区域">
          <!-- <el-option label="区域一" value="shanghai" /> -->
          <el-option v-for="item in ConstanEnum.hireType" :key="item.id" :label="item.value" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input v-model="form.workNumber" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <!-- 当你写代码发现，写不下去，一般是缺少了变量，需要增加变量 -->
        <el-input v-model="form.departmentName" readonly @focus="isShowTree = true" />
        <el-tree v-if="isShowTree" :data="data" :props="defaultProps" @node-click="handleNodeClick" />
      </el-form-item>
      <el-form-item label="转正时间" prop="correctionTime">
        <el-date-picker v-model="form.correctionTime" format="yyyy年MM月dd日" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button @click="cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import ConstanEnum from '@/constant/employees'
import { valideMobile } from '@/utils/validate'
import { getDepartmentInfoReqest } from '@/api/department'
import { transformListToTree2 } from '@/utils'
import { addUserRequest } from '@/api/employees'

// codeReview 提交了代码， 所谓的 pull request 提交pr
// 领导如果发现你的代码，两个地方的一模一样，一般就会要你重写
export default {
  name: 'DialogAdd',
  data() {
    const validateMobile = (rule, value, callback) => {
      // 正则校验手机号
      if (!valideMobile(value)) {
        callback(new Error('手机号不对'))
      } else {
        callback()
      }
    }
    return {
      // 导入的变量如果要直接使用到template模板里面
      ConstanEnum: ConstanEnum,
      form: {
        username: '',
        mobile: '',
        timeOfEntry: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        correctionTime: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }

        ],
        mobile: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '请输入活动名称', trigger: 'change' }
        ],
        formOfEmployment: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        workNumber: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请输入活动名称', trigger: 'change' }
        ],
        correctionTime: [
          { required: true, message: '请输入活动名称', trigger: 'change' }
        ]
      },
      data: [],
      defaultProps: {
        children: 'children',
        // label: 'label'
        label: 'name' // 页面上要显示的字段名称
      },
      isShowTree: false
    }
  },
  created() {
    this.getDepartmentInfo()
  },
  methods: {
    onSubmit() {
    //   console.log(this.form)
      this.$refs.formRef.validate(val => {
        // 所有表单字段 都校验成功了以后, val 就是true
        if (val) {
          // 兜底校验: 只有请求都成功以后才能发起请求
          // 如果校验失败,比如手机号输入错误,前段就可以发现的错误,就通知用户自己去修改
          // 就不可以发请求,由后端去校验,减轻了服务器的压力
          this.addUser()
        }
        console.log(val)
      })
    },
    async addUser() {
      try {
        const res = await addUserRequest(this.form)
        console.log('addUserRequest: ', res)
        if (res.success) {
          this.$emit('success')
          this.$message.success('新增成功')
        } else {
          this.$message.success('新增失败')
        }
      } catch (err) {
        console.log('addUserRequest: ', err)
      }
    },
    async getDepartmentInfo() {
      try {
        const res = await getDepartmentInfoReqest()
        // 删除掉数组的第一项，因为他是公司的信息
        res.data.depts.shift()
        // 将返回的值赋值给data， 并且渲染到el-tree上面； 用了一个公共的方法： 平铺结构转树形结构
        this.data = transformListToTree2(res.data.depts, '')
        console.log('getDepartmentInfoReqest: ', res)
      } catch (err) {
        console.log('getDepartmentInfoReqest: ', err)
      }
    },
    handleNodeClick(val) {
      console.log(val)
      // if else的代码可以使用 return优化，
      // 真正工作里面，如果只有if else两个条件，那么一般不会出现else
      // 一般使用 return中断函数的执行 --- 我之前项目的优化点， 合理地使用 return 代替 else 语句
      if (val.children?.length > 0) {
        return
      }
      this.form.departmentName = val.name
      // 关闭部门的tree
      this.isShowTree = false
    },
    cancle() {
      this.$emit('close')
    }
  }
}
</script>
